import db from '../utils/dbconf';
import makeres from '../utils/res';
import TokenTools from './tools/token';
import CodeTools from './tools/code';
import { ParameterError, AuthError, TargetDataNoneError } from '../utils/classModal';

import { TABLE_NAME as USER_TABLE } from './user';
import { Random } from 'mockjs';

// 查询用户列表
const tools_getlist = async (where, page, size) => {
	const { count: total, data: list } = await db.table(USER_TABLE).where(where).page(page, size).countSelect();
	return { total, list };
};

export const getlist = async ({ query }, res) => {
	const { u_id, level } = res.locals;
	const { page = 1, size = 10, name = '', inuse = 2 } = query;
	const where = { nickname: ['LIKE', `%${name}%`], dis: ['!=', inuse], u_id };
	if (level === 999) {
		// 处理super 的特殊筛选
		let { u_id, level } = query;
		if (!Number(u_id)) u_id = ['EXP', 'IS NOT NULL']; // 查询全部
		if (!Number(level)) level = ['EXP', 'IS NOT NULL'];
		Object.assign(where, { u_id, level });
	}
	const resdata = await tools_getlist(where, page, size);
	return res.send(makeres.success(resdata));
};

export const getdetail = async ({ params: { id } }, res) => {
	return res.send(makeres.success({ id }));
};

export const add = async ({ body: { account, password, nickname } }, res) => {
	const { u_id } = res.locals;
	/**
	 * === 上限查询 ===
	 */
	// const now = await db.table(USER_TABLE).where({ u_id }).count('id');
	// const max = await db.table()
	const { id, type } = await db.table(USER_TABLE).thenAdd({ account, password, nickname, u_id }, { account }, true);
	if (type === 'exist') throw new Error('添加失败，账号重复了');
	return res.send(makeres.success({ id }));
};

// export const change = async ({ params: { id }, body: data }, res) => {
// 	const { u_id } = res.locals;
// 	const ok = await db.table(USER_TABLE).where({ id }).update(data);
// 	if (!ok) throw new TargetDataNoneError();
// 	return res.send(makeres.putsuccess());
// };

export const deleteu = async ({ params: { id }, query: { t: password } }, res) => {
	const { u_id } = res.locals;
	if (u_id == id) throw new Error('不能操作自己！');
	const passok = await db.table(USER_TABLE).where({ password, id: u_id }).count('id');
	if (!passok) throw new Error('管理员密码错误');
	const ok = await db.table(USER_TABLE).where({ id, u_id }).delete();
	if (!ok) throw new TargetDataNoneError();
	return res.send(makeres.deletesuccess());
};

export const resetpass = async ({ params: { id } }, res) => {
	const { u_id } = res.locals;
	if (u_id == id) throw new Error('不能操作自己！');
	const password = Random.string(10);
	const ok = await db.table(USER_TABLE).where({ id, u_id }).update({ password });
	if (!ok) throw new TargetDataNoneError();
	await TokenTools.clearToken(id);
	return res.send(makeres.success({ password }, '重置密码成功'));
};

export default {
	getdetail,
	getlist,
	add,
	// change,
	delete: deleteu,
	resetpass,
};
